# -*- coding: utf-8 -*-


# cmap2owl -- Helper application to convert from concept maps to OWL ontologies
# Copyright (c) 2008-2013  Rodrigo Rizzi Starr
#  
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#  
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#  
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.


'''
Contains a set of rules to identify superclass/subclass relationships

@author: Rodrigo Rizzi Starr
@copyright: Copyright © 2008-2013 Rodrigo Rizzi Starr
@license: MIT License
@contact: rodrigo.starr@gmail.com
'''


from CMap2Prolog import assemblyQuery
from mapperRule import MapperRule
from toogleQuestion import ToogleQuestion
from infoProvider import InfoProvider, SimpleInfoProvider, UnionOfInfoProviders
from actionProvider import ActionProvider, UnionOfActionProviders
from log import log
log.debug('Loaded...')


class CompositionRule(MapperRule):
    'Looks for part-whole relationships'
    
    def __init__(self, db):
        
        classifiers = [
                       'hasPartPhrases',
                       'partOfPhrases',
                        ]
        
        # Heuristics to identify composition rules
        rules = [
                 'inferenceGroup(hasPartRule,'
                    '[hasPart(_, _, _)])',
                 
                 'hasPart(Relation, Owner, PartSet) :- '
                    'hasPartPhrases(Label), '
                    'label(Relation, Label), '
                    'linkingPhrase(Relation), '
                    'fromSetRelation(Relation, FromSet), '
                    'member(Owner, FromSet), '
                    'toSetRelation(Relation, PartSet) ',
                 
                 'hasPart(Relation, Owner, PartSet) :- '
                    'partOfPhrases(Label), '
                    'label(Relation, Label), '
                    'linkingPhrase(Relation), '
                    'toSetRelation(Relation, ToSet), '
                    'member(Owner, ToSet), '
                    'fromSetRelation(Relation, PartSet)',
                 
                 # Consequences
                  'isFalse(relation(Relation)) :-'
                    'isTrue(hasPart(Relation, _, _))',
                    
                 'hasPartClassesOWL(Class, ClassSet) :-'
                   'isTrue(hasPart(_, Class, ClassSet))',

                 'isTrue(class(Owner)) :- '
                    'isTrue(hasPart(_, Owner, _))',
                   
                 'isTrue(class(Part)) :- '
                    'isTrue(hasPart(_, _, PartSet)), member(Part, PartSet)',
                    ]
         
        MapperRule.__init__(self, 'MereologyRule', db, rules, classifiers)
          
    def getQuestions(self):
        'Returns a question list'
        questions = []
        query = 'possible(hasPart(Relation, FromClass, ToSet))'
        relations = list(self.db.query(query))
        
        for answer in relations:
            questions.append(HasPartQuestion(
                    self.db,
                    answer,
                    'The relation "<b>%(Relation)s</b>" seems to say that '
                        'some of the concepts below are a part of '
                        '"<b>%(FromClass)s</b>". Can you tell me which ones?',
                    helpFile = 'composition',
                    singularQuestion = 'Is "<b>%(ToSet)s</b>" a part of '
                        '"<b>%(FromClass)s</b>"?',
                 ))
            
        return questions
      
    def getInfoProvider(self):
        'Returns an info provider about mereological relations'
        
        relationInfo = SimpleInfoProvider(self.db,
                            'isTrue(hasPart(%s, _, _))',
                            'This link has been defined as a part-of relation')
        
        ownerInfo = InfoProvider(self.db,
                            'isTrue(hasPart(_, %s, Set))',
                            'This element is composed by:')
        
        partInfo = InfoProvider(self.db,
                            'isTrue(hasPart(_, El, PartSet)), '
                                'member(%s, PartSet), Set = [El]',
                            'This element is part of:')
        
        return UnionOfInfoProviders(relationInfo, ownerInfo, partInfo)
      
    def getActionsProvider(self):
        '''Returns actions providers for this rule'''
        
        hasPartProvider = ActionProvider(self.db,
                                'equivalentLinkingPhrase(Element, %s),'
                                        'label(Element, Label),'
                                        '\+ hasPartPhrases(Label)',
                                'Does this phrase '
                                        'indicate a has-part relation ?',
                                'hasPartPhrases(%(Label)s)')
        
        partOfProvider = ActionProvider(self.db,
                                'equivalentLinkingPhrase(Element, %s),'
                                        'label(Element, Label),'
                                        '\+ partOfPhrases(Label)',
                                'Does this phrase '
                                        'indicate a part-of relation ?',
                                'partOfPhrases(%(Label)s)')
        
        return UnionOfActionProviders(hasPartProvider,
                                      partOfProvider)

    
class HasPartQuestion(ToogleQuestion):
    'Implements a better way of checking the has part relationship'
    
    def updateQueryData(self):
        'Creates a string representing a query'
        query = 'possible(hasPart(%(Relation)s, %(FromClass)s, %(ToSet)s)),' \
            '%(ToSet)s = NewSet, ' \
            '\+ (isFalse(hasPart(%(Relation)s, %(FromClass)s, OSet)),' \
                'member(OSet, %(ToSet)s))'
        
        self.queryData = assemblyQuery(query, self.data)
    
    def updateIds(self):
        'Return a set of updated ids'
        
        answer = list(self.db.query(self.queryIds))
        if len(answer) > 1:
            log.error('The answer for ' + self.queryIds + 
                      ' was more than 1 result long. This is weird.')
        if len(answer) == 0:
            self.ids = set()
        else:
            answer = answer[0]['NewSet']
            self.data['NewSet'] = answer
            self.ids = set(([el for el in answer]))
            self.ids.add(self.data['Relation'])
            self.ids.add(self.data['FromClass'])
                       
    def updateChoices(self):
        'Return a set of updated choices'
        
        try:
            self.choices = self.ids.copy()
            self.choices.remove(self.data['Relation'])
            self.choices.remove(self.data['FromClass'])
        except KeyError:
            self.choices = set()
     
    def assertOnYes(self):
        'Asserts an updated set of elements'
        
        activeIds = self.getActiveIds()
        self.data['NewSet'] = activeIds
        
        queries = [assemblyQuery(
                    'isTrue(hasPart(%(Relation)s, %(FromClass)s, %(NewSet)s))',
                    self.data)]
        
        if len(activeIds) < len(self.middle):
            # So we know not all options were selected
            # This entails that the group as a whole is not disjoint
            self.data['OtherSet'] = self.ids - activeIds
            queries.append(assemblyQuery(
                    'isFalse(hasPart(%(Relation)s, '
                           '%(FromClass)s, %(OtherSet)s))',
                     self.data))
        
        return queries
    
    def assertOnNo(self):
        'Creates a string representing a question'
        
        queries = assemblyQuery(
                    'isFalse(hasPart(%(Relation)s, %(FromClass)s, %(ToSet)s))',
                    self.data)
        
        return [queries]
      
